#include "nbook.h"
#include "ui_nbook.h"

Nbook::Nbook(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Nbook)
{
    ui->setupUi(this);
    connect(ui->cancel, &QPushButton::clicked, this, &Nbook::cc);
    connect(ui->YesButton, &QPushButton::clicked, this, &Nbook::save);
}

Nbook::~Nbook()
{
    delete ui;
}

void Nbook::cc() {
    this->close();
}

void Nbook::save() {
    QString BookID = ui->BookID->text();
    QString Bname = ui->Bname->text();
    QString Press = ui->Press->text();
    QString Store = ui->Store->text();
    QDateEdit *dateEdit = ui->BDate;
    QString BDate = dateEdit->date().toString("yyyy-MM-dd");

    // 验证输入不为空
    if (BookID.isEmpty() || Bname.isEmpty() || BDate.isEmpty() || Press.isEmpty()|| Store.isEmpty()) {
        QMessageBox::warning(this, "错误", "请填写所有必要信息！");
        return;
    }

    // 执行SQL插入
    QSqlDatabase db = QSqlDatabase::database("qt_sql_default_connection");
    if (!db.isOpen()) {
        QMessageBox::warning(this, "错误", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    query.prepare("INSERT INTO BuyList (BookID, Bname, Press, Store, BDate) "
                  "VALUES (?, ?, ?, ?, ?)");
    query.addBindValue(BookID);
    query.addBindValue(Bname);
    query.addBindValue(Press);
    query.addBindValue(Store);
    query.addBindValue(BDate);

    if (query.exec()) {
        QMessageBox::information(this, "成功", "数据添加成功！");
        this->close();  // 关闭窗口
    } else {
        QMessageBox::critical(this, "错误",
                              QString("数据添加失败"));
    }
}
